package org.dreamwork.assistant.tools.network.gui;

import org.apache.log4j.Logger;
import org.dreamwork.util.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by seth.yang on 2018/5/7
 */
public class TcpReader extends NetworkReader {
    private final Logger al = Logger.getLogger (TcpReader.class);
    private InputStream in;

    TcpReader (InputStream in/*, IMessageLogger logger*/) {
        super (/*logger, */"TCP Reader");
        this.in = in;
    }

    @Override
    protected void doWork () {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream ();
            byte[] buff = new byte[1024];
            int length;
            while ((length = in.read (buff)) != -1) {
                baos.write (buff, 0, length);
                if (length < buff.length) {
                    byte[] data = baos.toByteArray ();
                    al.info ("received data: " + StringUtil.format (data));
//                    logger.append (data);
                    baos.reset ();
                    if (listener != null) {
                        listener.onReceived (data);
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace ();
        }
    }

    @Override
    public void shutdown () {

    }
}
